# 躲避游戏
import pygame
import random

# 初始化 Pygame
pygame.init()

# 设置屏幕大小
screen_width = 600
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))

# 设置标题
pygame.display.set_caption("Dodge Game")

# 设置玩家属性
player_size = 50
player_x = screen_width / 2
player_y = screen_height - player_size
player_speed = 10

# 设置障碍物属性
obstacle_width = 50
obstacle_height = 50
obstacle_x = random.randint(0, screen_width - obstacle_width)
obstacle_y = 0
obstacle_speed = 5

# 设置游戏循环的标志
running = True

# 设置游戏循环的帧率
clock = pygame.time.Clock()

# 游戏主循环
while running:
    # 填充背景色
    screen.fill((255, 255, 255))

    # 事件监听
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 玩家控制
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and player_x > 0:
        player_x -= player_speed
    if keys[pygame.K_RIGHT] and player_x < screen_width - player_size:
        player_x += player_speed

    # 障碍物移动
    obstacle_y += obstacle_speed
    if obstacle_y > screen_height:
        obstacle_y = 0
        obstacle_x = random.randint(0, screen_width - obstacle_width)

    # 绘制玩家
    pygame.draw.rect(screen, (0, 0, 255), (player_x, player_y, player_size, player_size))

    # 绘制障碍物
    pygame.draw.rect(screen, (255, 0, 0), (obstacle_x, obstacle_y, obstacle_width, obstacle_height))

    # 更新屏幕
    pygame.display.flip()

    # 控制游戏帧率
    clock.tick(30)

    # 在玩家控制和障碍物移动代码块之后
    # 检测玩家和障碍物是否碰撞
    if player_x < obstacle_x + obstacle_width and \
            player_x + player_size > obstacle_x and \
            player_y < obstacle_y + obstacle_height and \
            player_y + player_size > obstacle_y:
        # 碰撞发生时的代码
        print("碰撞发生了！")
        # 例如，可以让玩家的位置重置到屏幕中间
        player_x = screen_width / 2

# 退出 Pygame
pygame.quit()